package com.sunxueqi.framework.web.vo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.http.HttpStatus;

import com.github.pagehelper.PageInfo;

import cn.hutool.core.util.ObjectUtil;

public class ResponseData extends HashMap<String, Object>{
	public static final String CODE = "code";
	/**
	 * 消息内容
	 */
	public static final String MESSAGE = "message";
	
	/**
	 * 数据对象
	 */
	public static final String DATA = "data";
	
	/**
	 * 数据总数
	 */
	public static final String TOTAL = "total";
	
	
	public ResponseData () {
	}
	
	public ResponseData (int code, String message) {
		super.put(CODE, code);
		super.put(MESSAGE, message);
	}
	
	public ResponseData (HttpStatus code, String message, Object data) {
		super.put(CODE, code.value());
		super.put(MESSAGE, message);
		if(ObjectUtil.isNotNull(data)) {
			super.put(DATA, data);
		}
	}
	
	/**
	 * 只返回成功的code
	 */
	public static ResponseData success () {
		return ResponseData.success("操作成功");
	}
	
	/**
	 * 只返回成功的data
	 * @param data 数据对象
	 * @return
	 */
	public static ResponseData success (Object data) {
		return ResponseData.success("操作成功", data);
	}
	
	/**
	 * 只返回成功的自定义message
	 * @param message 消息内容
	 * @return
	 */
	public static ResponseData success (String message) {
		return ResponseData.success(message, null);
	}
	
	/**
	 * 返回成功的自定义message和data
	 * @param message 消息内容
	 * @param data 数据对象
	 * @return
	 */
	public static ResponseData success (String message, Object data) {
		return new ResponseData(HttpStatus.OK, message, data);
	}
	
	/**
	 * 返回成功相应的table数据
	 * @param list
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static ResponseData successTableData (List<?> list) {
		if(list == null) {
			list = new ArrayList<>();
		}
		ResponseData respData = new ResponseData(HttpStatus.OK, "操作成功", list);
		respData.put(TOTAL, new PageInfo(list).getTotal());
		return respData;
	}

	
	/**
	 * 返回错误消息
	 * @return
	 */
	public static ResponseData error () {
		return error("操作失败");
	}
	
	/**
	 * 返回错误的自定义message
	 * @param message 自定义message
	 * @return
	 */
	public static ResponseData error (String message) {
		return error(message, null);
	}
	
	/**
	 * 返回message和data
	 * @param message
	 * @param data
	 * @return
	 */
	public static ResponseData error(String message, Object data) {
		return new ResponseData(HttpStatus.INTERNAL_SERVER_ERROR, message, data);
	}
	
	/**
	 * 返回自定义的code和message
	 * @param code 自定义code
	 * @param message 自定义message
	 * @return
	 */
	public static ResponseData error (int code, String message) {
		return new ResponseData(code, message);
	}
}
